<template>
    <div>
        <div v-if="showSwitch && isAdmin" class="user-select-box">
            <el-select
                v-model="chosedUser"
                :model="chosedUser"
                :remote-method="selectUser"
                :disabled="isMockUserExist"
                placeholder="学号或工号搜索"
                style="width:130px"
                filterable
                size="mini"
                remote
            >
                <el-option
                    v-for="item in users"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
            <i slot="suffix" class="el-icon-search" />
            <el-button v-if="!isMockUserExist" type="text" @click="switchAccount">
                切换用户
            </el-button>
            <el-button v-else type="text" @click="cancelMock">取消切换</el-button>
        </div>
        <!-- 教学评价模块，强制填写问卷弹窗 未做完问卷不允许其他操作 -->
        <!-- 问卷列表 -->
        <el-dialog
            v-drag-dialog
            width="80%"
            :visible.sync="dialogShow"
            :close-on-click-modal="false"
            :show-close="ifShowClose"
            :fullscreen="false"
            :close-on-press-escape="false"
        >
            <template v-if="ifStudent">
                <ForcePageOfStu
                    @goBackAndCheckForceState="goBackAndCheckForceState"
                ></ForcePageOfStu>
            </template>
            <template v-if="ifTeacher">
                <ForcePageOfTeacher
                    @goBackAndCheckForceState="goBackAndCheckForceState"
                ></ForcePageOfTeacher>
            </template>
        </el-dialog>
    </div>
</template>
<script>
import { findTopTenUserList } from 'common/src/api/user'
import { mock, mockOff } from 'common/src/api/session'
import Bus from 'common/src/utils/bus'
import questionnaireApi from 'common/src/api/teachingEvaluation/questionnaire'
import ForcePageOfStu from 'common/src/views/teachingEvaluation/ForcePageOfStu'
import ForcePageOfTeacher from 'common/src/views/teachingEvaluation/ForcePageOfTeacher'
import questionnaireWriteOfTeacher from 'common/src/views/teachingEvaluation/questionnaireWriteOfTeacher'
import SchoolCalendarApi from 'common/src/api/calendars'
import mixin from 'common/src/mixins/index'
export default {
    name: 'UserSelect',
    inject: ['reload'],
    mixins: [mixin],
    props: {
        mockUser: Object,
        showSwitch: Boolean
    },
    components: {
        ForcePageOfStu,
        ForcePageOfTeacher,
        questionnaireWriteOfTeacher
    },
    data() {
        const mockUserName = () => {
            const cur = this.$props.mockUser
            if (cur != null && cur != undefined) return this.getMockUserName(cur)
            else return ''
        }
        return {
            userList: [],
            users: [],
            chosedUser: mockUserName(),
            isAdmin: false, // 是否为超级管理员
            dialogShow: false,
            ifShowClose: false,
            ifStudent: false,
            ifTeacher: false,
            queryParams: {
                calendarId: ''
            }
        }
    },
    created() {
        this.judgmentIsAdmin()
        // 判断角色权限
        Bus.$on('updateCurrentRole', () => {
            this.judgmentIsAdmin()
        })
        this.writeQuestionnaireForce()
    },
    mounted() {
        if (document.getElementsByClassName('el-select').length) {
          // v-clearreadonly指令不生效，现单独实现去除readonly属性
          Array.from(document.getElementsByClassName('el-select')).forEach(item => {
            if (item.children.length && item.children[0].children.length) {
              item.children[0].children[0].removeAttribute('readonly');
              item.children[0].children[0].onblur = function() {
                  let _this = this
                  setTimeout(() => {
                      if (_this.getAttribute('readonly')) {
                          _this.removeAttribute('readonly');
                      }
                  }, 200)
              }
              item.children[0].children[0].onclick = function () {
                const _this = this;
                setTimeout(() => {
                  if (_this.getAttribute('readonly')) {
                      _this.removeAttribute('readonly');
                  }
                }, 200)
              }
            }
          });
        }
    },
    computed: {
        isMockUserExist() {
            return this.$props.mockUser != null || this.$props.mockUser != undefined
        },
        currentUser: {
            get() {
                if (this.$store.state.session.user) {
                    return this.$store.state.session.user
                }
                return JSON.parse(localStorage.getItem('user'))
            }
        }
    },
    watch: {
        mockUser(val) {
            this.chosedUser = this.getMockUserName(val)
        }
    },
    methods: {
        getMockUserName(val) {
            return val.name
                .concat('(')
                .concat(val.uid)
                .concat(')')
        },
        switchAccount() {
            if (!this.chosedUser) {
                this.$message({
                    type: 'warning',
                    message: '请选择要切换的用户'
                })
                return
            }

            const data = {
                mockUid: this.chosedUser,
                mockUserType: _.filter(this.userList, { userId: this.chosedUser })[0].userType
            }
            mock(data)
                .then(res => {
                    if (res.code == 200) this.reloadPage(res.data)
                    else if(res.code == 313){
                        this.$message({
                            type: 'error',
                            message: '该账号已冻结，请激活后再尝试'
                        })
                    }
                    else throw res.code
                })
                .catch(error => {
                    this.$message({
                        type: 'error',
                        message: '切换失败, 请重试'
                    })
                })
        },
        cancelMock() {
            mockOff()
                .then(res => {
                    if (res.code == 200) this.reloadPage(res.data)
                    else throw res.code
                })
                .catch(error => {
                    this.$message({
                        type: 'error',
                        message: '操作失败, 请重试'
                    })
                })
        },
        reloadPage(data) {
            this.reload()
            this.$router.replace({
                name: 'workbench'
            })
            this.$store.commit('clear_tab_info')
            this.$store.state.common.activeIndex = '/workbench'
            this.$store.commit('set_session_data', data)
            if (data && data.mockUser) {
                this.$emit('updateCurrentManageDptId', data.mockUser.currentManageDptId)
            }
            this.$message({
                type: 'success',
                message: '操作成功'
            })
        },
        selectUser(query) {
            if (!query) return
            const data = { userId: query }
            this.loading = true
            findTopTenUserList(data)
                .then(res => {
                    this.loading = false
                    if (res.code == 200) {
                        this.userList = res.data
                        this.users = this.transData(res.data)
                    } else throw res.code
                })
                .catch(error => {
                    this.loading = false
                    this.$message({
                        type: 'error',
                        message: '查询用户出错'
                    })
                })
        },
        transData(list) {
            return list.map((item, index, array) => {
                return {
                    label: item.userName + '(' + item.userId + ')',
                    value: item.userId
                }
            })
        },
        // 判断是否为超级管理员
        judgmentIsAdmin() {
            // 判断是否未本地角色、管理员、内置角色是否有管理员、uid是否为admin1
            let isCurrentUser, isCurrentRole, isAdmin
            if (!this.currentUser) return
            if (this.currentUser.type === 3) isCurrentUser = true
            if (this.currentUser.currentRole === '1') isCurrentRole = true
            if (this.currentUser.uid === 'admin1' || this.currentUser.uid === 'sysAdmin1')
                isAdmin = true
            if (isCurrentUser && isCurrentRole && isAdmin) this.isAdmin = true
            else this.isAdmin = false
        },
        // 获取当前学年学期
        async getCurrentTermCalendar() {
            return await SchoolCalendarApi.currentTermCalendar()
        },
        // 教学评价模块，强制填写问卷弹窗 未做完问卷不允许其他操作
        // 获取当前登录用户是否需要强制填写问卷
        writeQuestionnaireForce() {
            const mockUser = JSON.parse(localStorage.getItem('sessiondata'))
                ? JSON.parse(localStorage.getItem('sessiondata')).mockUser || this.currentUser
                : null
            if (mockUser) {
                if (mockUser.type == 2) {
                    this.ifStudent = true
                    this.ifTeacher = false
                    this.getCurrentTermCalendar().then(resp => {
                        this.queryParams.calendarId = resp.data.schoolCalendar.id
                        questionnaireApi.getForceStudent(this.queryParams).then(res => {
                            if (!res.data) {
                                this.dialogShow = false
                            } else {
                                this.$confirm(
                                    '您有待办事项需要完成，请去完成待办事项，否则无法进行其他操作！',
                                    '温馨提示',
                                    {
                                        confirmButtonText: '确定',
                                        showCancelButton: false,
                                        closeOnPressEscape: false,
                                        closeOnClickModal: false,
                                        showClose: false,
                                        type: 'warning'
                                    }
                                ).then(_ => {
                                    this.dialogShow = true
                                })
                            }
                        })
                    })
                } else if (mockUser.type == 1) {
                    this.ifStudent = false
                    this.ifTeacher = true
                    let currentUser = this.global.currentUser
                    questionnaireApi.getForceTeacher().then(res => {
                        if (res.data && currentUser.currentManageDptId) {
                            if (currentUser.currentManageDptId !== '2') {
                                if (currentUser.manageDptIds.indexOf('2') >= 0) {
                                    Bus.$emit('goToPost')
                                } else {
                                    return
                                }
                            } else {
                                this.$confirm(
                                    '您有待办事项需要完成，请去完成待办事项，否则无法进行其他操作！',
                                    '温馨提示',
                                    {
                                        confirmButtonText: '确定',
                                        showCancelButton: false,
                                        closeOnPressEscape: false,
                                        closeOnClickModal: false,
                                        showClose: false,
                                        type: 'warning'
                                    }
                                ).then(_ => {
                                    this.dialogShow = true
                                })
                            }
                        } else {
                            return
                        }
                    })
                }
            }
        },
        // 提交完成之后回到当前页面判断是否需要关闭弹窗
        goBackAndCheckForceState() {
            if (this.ifStudent) {
                questionnaireApi.getForceStudent(this.queryParams).then(res => {
                    if (!res.data) {
                        this.dialogShow = false
                    } else {
                        this.dialogShow = true
                    }
                })
            } else if (this.ifTeacher) {
                questionnaireApi.getForceTeacher().then(res => {
                    if (!res.data) {
                        this.dialogShow = false
                    } else {
                        this.dialogShow = true
                    }
                })
            }
        }
    }
}
</script>
<style lang="scss" scoped>
</style>
